package abd.pr2.bd;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.xquery.XQConnection;
import javax.xml.xquery.XQDataSource;
import javax.xml.xquery.XQException;
import javax.xml.xquery.XQPreparedExpression;
import javax.xml.xquery.XQResultSequence;

public abstract class ConsultaAbstracta<T> {

	private XQDataSource xqds;
	protected String nombreArchivo;
	
	public ConsultaAbstracta(XQDataSource xqds){
		this.xqds = xqds;
	}
	
	public List<T> ejecuta(){
		
		XQConnection con = null;
		XQPreparedExpression exp = null;
		XQResultSequence rs = null;
		
		try {
			InputStream is = new FileInputStream(nombreArchivo);
			
			con = this.xqds.getConnection();
			exp = con.prepareExpression(is);
			addBinds(exp);
			
			rs = exp.executeQuery();
	       
			List<T> elementos = new ArrayList<>();
			
			while (rs.next()){
				elementos.add(buildObject(rs));
			}
			
			return elementos;
			
		} catch (FileNotFoundException e) {
			System.out.println("No se encuentra el archivo "+nombreArchivo);
			e.printStackTrace();
		} catch (XQException e) {
			System.out.println("Fallo en la conexion o consulta");
			e.printStackTrace();
		} finally {
			try{
				rs.close();
				exp.close();
				con.close();
			} catch(Exception e){}
		}

		
		return null;
	}
	
	public abstract void addBinds(XQPreparedExpression exp) throws XQException;
	
	public abstract T buildObject(XQResultSequence rs) throws XQException;
	
}

